package com.liu.yupao.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.yupao.common.BaseResponse;
import com.liu.yupao.common.ErrorCode;
import com.liu.yupao.common.ResultUtils;
import com.liu.yupao.exception.BusinessException;
import com.liu.yupao.model.dto.user.UserUpdateRequest;
import com.liu.yupao.model.entity.User;
import com.liu.yupao.model.dto.user.UserLoginRequest;
import com.liu.yupao.model.dto.user.UserRegisterRequest;
import com.liu.yupao.model.vo.UserVO;
import com.liu.yupao.service.UserService;
import com.liu.yupao.utils.CopyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import java.util.List;
import java.util.stream.Collectors;

import static com.liu.yupao.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"账号或密码不能为空");
        }
        UserVO user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<UserVO> getCurrentUser(HttpServletRequest request) {
        User currentUser = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        UserVO safetyUser = CopyUtils.copy (user, UserVO.class);
        return ResultUtils.success(safetyUser);
    }


    @GetMapping("/search")
    public BaseResponse<List<UserVO>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> list = userList.stream().map(user -> CopyUtils.copy(user,UserVO.class)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<UserVO>> searchUsersByTags(@RequestParam List<String> tagList){
        if (CollUtil.isEmpty (tagList)){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> userVOS = userService.searchUsersByTags (tagList);
        return ResultUtils.success (userVOS);
    }

    @GetMapping("/recommend")
    public BaseResponse<List<UserVO>> recommendUsers(long current,long pageSize,HttpServletRequest request){
        //限制爬虫
        if (pageSize>=30){
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"分页条数过长!");
        }
        //获取服务层执行结果
        Page<User> userPage = userService.recommendUsers (current, pageSize, request);
        List<User> userList = userPage.getRecords ();
        //返回脱敏数据
        return ResultUtils.success (userList.stream ().
                map (UserVO::toUserVO).collect(Collectors.toList()));
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request){
        //校验参数
        if (userUpdateRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //进行判断
        int result = userService.updateUser (userUpdateRequest, request);
        return ResultUtils.success (result);
    }

    @GetMapping("/match")
    public BaseResponse<List<UserVO>> matchUsers(Long num,HttpServletRequest request){
        if (num<=0 || num>20){
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"最多获取20条用户数据!");
        }
        List<UserVO> matchUsers = userService.match (num, request);
        return ResultUtils.success (matchUsers);
    }
}
